import { loginAPI, getUserProfileAPI, getUserPhotoAPI } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import store from '@/store'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken() || '',
    userInfo: {}
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    // assigin 可以合并两个对象 get...（）方法里面rentun存在 token:''会将token清空
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  REMOVE_TOKEN(state) {
    state.token = ''
    removeToken()
  },
  SET_USER(state, value) {
    state.userInfo = value
  },
  // 设置头像
  REMOVE_USER(state) {
    state.userInfo = {}
  }
}

const actions = {
  async loginActions({ commit }, value) {
    const [err, res] = await loginAPI(value)
    if (!err) commit('SET_TOKEN', res.data)
    return [err, res]
  },
  async getUserInfoActions({ commit }) {
    const { data: userObj } = await getUserProfileAPI()
    const { data: photoObj } = await getUserPhotoAPI(userObj.userId)
    commit('SET_USER', { ...userObj, ...photoObj })
  },
  async logoutActions({ commit }) {
    console.log('lgllglglg')
    removeToken()
    store.commit('user/REMOVE_TOKEN')

    router.replace(`/login?redirect=${router.currentRoute.fullPath}`)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
